package com.emergency.db.service.impl.item;

import com.emergency.common.util.CommonUtils;
import com.emergency.common.util.IdWorker;
import com.emergency.db.dao.item.ItemDao;
import com.emergency.db.dao.item.ItemDetailDao;
import com.emergency.db.dao.item.ItemUserDao;
import com.emergency.db.domain.item.Item;
import com.emergency.db.domain.item.ItemDetail;
import com.emergency.db.domain.item.ItemUser;
import com.emergency.db.domain.staff.Staff;
import com.emergency.db.service.item.ItemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

//应急监测与辐射防护设备
@Service
public class ItemServiceImpl implements ItemService {

    private final static Logger logger = LoggerFactory.getLogger(ItemServiceImpl.class);

    @Autowired
    private ItemDao itemDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private ItemDetailDao itemDetailDao;

    @Autowired
    private ItemUserDao itemUserDao;

    //保存
    public Long save(Item item) {
        if (CommonUtils.isNullOrEmpty(item.getId())) {
            item.setId(idWorker.nextId());
            item.setCreateTime(new Date());
        }
        //保存装备细则信息
        itemDao.save(item);
        //保存装备基本信息
        detailSave(item);
        //保存装备配置人员信息
        userSave(item);
        return item.getId();
    }

    private void detailSave(Item item) {
        ItemDetail itemDetail = item.getItemDetail();
        if (CommonUtils.isNullOrEmpty(itemDetail.getId())) {
            itemDetail.setId(idWorker.nextId());
            itemDetail.setItem(item);
        }
        itemDetailDao.save(itemDetail);
    }

    private void userSave(Item item) {
        List<ItemUser> itemUsers = item.getItemUser();
        if (!CommonUtils.isNullOrEmpty(itemUsers)) {
            itemUsers.forEach(itemUser -> {
                itemUser.setId(idWorker.nextId());
                itemUser.setItem(item);
            });
        }
        itemUserDao.saveAll(itemUsers);
    }

    //批量保存
    public void saveAll(List<Item> itemList) {
        itemList.forEach(item -> {
            if (CommonUtils.isNullOrEmpty(item.getId())) {
                item.setId(idWorker.nextId());
                item.setCreateTime(new Date());
            }
            //保存装备细则信息
            itemDao.save(item);
            //保存装备基本信息
            detailSave(item);
            //保存装备配置人员信息
            userSave(item);
        });
    }

    //查询全部
    public List<Item> findAll() {
        List<Item> itemList = itemDao.findAll();
        itemList.forEach(item -> {
            item.setItemDetail(itemDetailDao.findByItem(item.getId()));
            item.setItemUser(itemUserDao.findAllByItem(item.getId()));
        });
        return itemList;
    }

    //查询单项
    public Item findById(Long id) {
        Item item = itemDao.findById(id).orElse(null);
        if (CommonUtils.isNullOrEmpty(item)) {
            logger.info("此装备信息为空！");
            return item;
        }
        item.setItemDetail(itemDetailDao.findByItem(id));
        item.setItemUser(itemUserDao.findAllByItem(id));
        return item;
    }


    //删除
    @Transactional
    public void delete(Long id) {
        itemUserDao.deleteAllByItem(id);
        itemDetailDao.deleteByItem(id);
        itemDao.deleteById(id);
    }

    //分页查询
    @Override
    public Page<Item> findList(Map searchMap, int page, int size) {
        Specification<Item> specification = createSpecification(searchMap);
        Sort sort = Sort.by(Sort.Direction.ASC, "id");
        PageRequest pageRequest = PageRequest.of(page - 1, size, sort);
        Page<Item> itemList = itemDao.findAll(specification, pageRequest);
        itemList.forEach(item -> {
            item.setItemDetail(itemDetailDao.findByItem(item.getId()));
            item.setItemUser(itemUserDao.findAllByItem(item.getId()));
        });
        return itemList;
    }

    /**
     * 动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<Item> createSpecification(Map searchMap) {
        return new Specification<Item>() {

            @Override
            public Predicate toPredicate(Root<Item> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<Predicate>();

                // 名称
                if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) {
                    predicateList.add(criteriaBuilder.like(root.get("name").as(String.class), "%" + (String) searchMap.get("name") + "%"));
                }
                // 设备型号
                if (searchMap.get("type") != null && !"".equals(searchMap.get("type"))) {
                    predicateList.add(criteriaBuilder.like(root.get("type").as(String.class), "%" + (String) searchMap.get("type") + "%"));
                }
                // 地址
                if (searchMap.get("address") != null && !"".equals(searchMap.get("address"))) {
                    predicateList.add(criteriaBuilder.like(root.get("address").as(String.class), "%" + (String) searchMap.get("address") + "%"));
                }
                //装备类型
                if (searchMap.get("itemClass") != null && !"".equals(searchMap.get("itemClass"))) {
                    predicateList.add(criteriaBuilder.equal(root.get("itemClass").as(Long.class), (Long) searchMap.get("itemClass")));
                }
                //负责人
                if (searchMap.get("manager") != null && !"".equals(searchMap.get("manager"))) {
                    predicateList.add(criteriaBuilder.like(root.get("manager").as(String.class), "%" + (String) searchMap.get("manager") + "%"));
                }
                //所属队
                if (searchMap.get("army") != null && !"".equals(searchMap.get("army"))) {
                    predicateList.add(criteriaBuilder.equal(root.get("army").as(String.class), (String) searchMap.get("army")));
                }
                //所属分队名下小组
                if (searchMap.get("sGroup") != null && !"".equals(searchMap.get("sGroup"))) {
                    predicateList.add(criteriaBuilder.equal(root.get("sGroup").as(String.class), (String) searchMap.get("sGroup")));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
    }
}
